package com.example.kotlindemo.modules.todolist

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.kotlindemo.R
import com.example.kotlindemo.adapter.CompletedTaskAdapter

class CompletedTasksFragment : Fragment() {

    // 获取与 Activity 共享的 ViewModel
    private val viewModel: TodoListViewModel by activityViewModels()
    private lateinit var completedTaskAdapter: CompletedTaskAdapter
    private lateinit var recyclerView: RecyclerView

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_completed_tasks, container, false)
        // 使用 findViewById 获取 RecyclerView
        recyclerView = view.findViewById(R.id.rvCompletedTasks)
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupRecyclerView()
        observeViewModel()
    }

    private fun setupRecyclerView() {
        completedTaskAdapter = CompletedTaskAdapter { task ->
            // 点击完成项的对勾 -> 标记为未完成
            viewModel.uncompleteTask(task)
        }
        recyclerView.adapter = completedTaskAdapter
        // LayoutManager 已在 XML 中设置
        // recyclerView.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)

        // 自定义动画
        recyclerView.itemAnimator = DefaultItemAnimator().apply {
            addDuration = 300
            removeDuration = 300
            moveDuration = 300
        }

        // 禁用焦点引起的自动滚动
        recyclerView.isFocusable = false
        recyclerView.descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS
        // 确保 LayoutManager 行为稳定
        (recyclerView.layoutManager as? LinearLayoutManager)?.let { layoutManager ->
            layoutManager.stackFromEnd = false
            layoutManager.reverseLayout = false
        }
    }

    private fun observeViewModel() {
        viewModel.completedTasks.observe(viewLifecycleOwner) { tasks ->
            val oldSize = completedTaskAdapter.currentList.size
            // 提交新数据，触发 ListAdapter 的动画
            completedTaskAdapter.submitList(tasks) {
                // submitList 的回调在数据提交完成后执行
                // tasks.size > oldSize 防止抖动
                if (!tasks.isNullOrEmpty() && tasks.size > oldSize) {
                    // 检查 RecyclerView 是否有 ItemAnimator
                    val animator = recyclerView.itemAnimator
                    if (animator != null && animator.isRunning) {
                        // 如果动画正在运行，等待动画完成
                        animator.isRunning {
                            // 动画完成后平滑滚动到顶部
                            recyclerView.smoothScrollToPosition(0)
                        }
                    } else {
                        // 如果没有动画，直接平滑滚动
                        recyclerView.smoothScrollToPosition(0)
                    }
                }
            }
        }
    }


    companion object {
        @JvmStatic
        fun newInstance() = CompletedTasksFragment()
    }
}